package itsm.isperp.module.controller.bpm;

import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.bpm.BpmProcessSetting;
import itsm.isperp.module.entity.db.DbEntity;
import itsm.isperp.module.service.bpm.BpmProcessSettingService;
import itsm.isperp.module.service.bpm.act.BpmActService;
import itsm.isperp.module.service.db.DbEntityService;
import itsm.isperp.workflow.graph.ShapeMeta;
import itsm.isperp.workflow.service.BpmProcessDefinitaionService;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 流程设置控制器
 * 
 * @author lizx
 * @date 2013-6-14
 */
@Controller
@RequestMapping("bpm/processSetting")
public class BpmProcessSettingController extends
		BaseController<BpmProcessSetting> {

	@Autowired
	BpmProcessSettingService bpmProcessSettingService;
	@Autowired
	BpmProcessDefinitaionService bpmProcessDefinitaionService;
	@Autowired
	DbEntityService dbEntityService;
	@Autowired
	BpmActService bpmActService;

	@Override
	public BpmProcessSettingService getService() {
		return bpmProcessSettingService;
	}

	@Override
	public String getPageTitle() {
		return "流程设置";
	}

	@RequestMapping("findProcessDbEntityList")
	@ResponseBody
	public List<DbEntity> findProcessDbEntityList() {

		return this.getService().findProcessDbEntityList();
	}

	@Override
	@RequestMapping("listDetail")
	public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
			HttpServletRequest req) {
		if (request.getSelectColumns() != null) {

			request.addSelectColumnsInFirst("DISTINCT 1 AS temp_col");
			request.addSelectColumnsInFirst("id");
		}

		PageResponse<Map<String, Object>> page = this.getService()
				.findAllDetailByRequest(request).toPage();
		for (Map<String, Object> m : page) {
			Object d = m.get("deploy_time");
			if (d != null && d instanceof oracle.sql.TIMESTAMP) {
				oracle.sql.TIMESTAMP t = (oracle.sql.TIMESTAMP) d;
				try {
					m.put("deploy_time", new java.sql.Timestamp(t.dateValue()
							.getTime()));
				} catch (SQLException e) {
					m.put("deploy_time", null);
				}
			}
		}

		return page;
	}

	/**
	 * 编辑界面
	 * 
	 * @param id
	 *            唯一标识
	 * @return 编辑视图
	 * @throws DocumentException
	 * @throws IOException
	 */
	@Override
	@RequestMapping(value = { "config", "edit" })
	public ModelAndView edit(String id, HttpServletRequest req)
			throws IOException, DocumentException {
		ModelAndView mv = new ModelAndView();
		BpmProcessSetting model = null;
		String processKey = req.getParameter("processKey");

		if (StringUtils.isEmpty(id)) {
			model = new BpmProcessSetting();

			// 流程key
			if (StringUtils.isEmpty(processKey)) {

			}
		} else {

			model = this.getService().findOne(id);
			DbEntity dbEntity = dbEntityService.findOne(model.getDbEntityId());
			if (dbEntity != null)
				mv.addObject("dbEntityName", dbEntity.getName());

			DbEntity dbForSlmEntity = dbEntityService.findOne(model
					.getDbForSlmEntityId());
			if (dbForSlmEntity != null)
				mv.addObject("dbForSlmEntityName", dbForSlmEntity.getName());

			ProcessDefinition processDefinition = bpmProcessDefinitaionService
					.getProcessDefinitionByKey(model.getActReProcdefKey());

			if (processDefinition.getDeploymentId() != null) {

				ShapeMeta shapeMeta = bpmProcessDefinitaionService
						.getProcessDefinitionShapeMeta(processDefinition);

				mv.addObject("shapeMeta", shapeMeta);
				mv.addObject("processDefinition", processDefinition);
				String modelId = this.bpmProcessDefinitaionService
						.getModelByDeploymentId(
								processDefinition.getDeploymentId()).getId();
				mv.addObject("modelId", modelId);

			}

		}

		mv.addObject("model", model);
		mv.addObject("pageTitle", this.getPageTitle());
		mv.setViewName(this.getModulePath() + "/edit");
		return mv;
	}

	@RequestMapping(value = "assignmentsEdit/{defId}")
	public ModelAndView assignmentsEdit(
			@PathVariable("defId") String processDefinitionId,
			HttpServletResponse response) throws Exception {

		ModelAndView mv = new ModelAndView("workflow/process/assignmentsEdit");
		ProcessDefinitionEntity pd = bpmProcessDefinitaionService
				.getProcessDefinitionEntityById(processDefinitionId);
		List<ActivityImpl> activitiList = pd.getActivities();

		List<TaskDefinition> tasks = new ArrayList<TaskDefinition>();

		for (ActivityImpl act : activitiList) {
			Object taskDefinition = act.getProperty("taskDefinition");

			if (act.isExclusive()) {
				// System.out.println(act.getProperty("name"));
				if (taskDefinition instanceof TaskDefinition) {
					TaskDefinition task = (TaskDefinition) taskDefinition;
					tasks.add(task);

				}

			}
		}
		mv.addObject("tasks", tasks);
		return mv;
	}

	@RequestMapping(value = "getDbEntityColumnByProcDefKey")
	@ResponseBody
	public List<Map<String, Object>> getDbEntityColumnByProcDefKey(
			String processKey) {
		return this.getService().findDbEntityColumnByProcDefKey(processKey);
	}
	
	@RequestMapping(value = "getStartFormByProcDefKey")
	@ResponseBody
	public String getStartFormByProcDefKey(
			String processKey) {
		return this.getService().getStartFormByProcDefKey(processKey);
	}
}
